package com.me.modules.common.utils;


import com.me.modules.common.xss.SQLFilter;
import org.apache.commons.collections4.MapUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 查询参数
 *
 * @author jindouyun
 */
public class Query extends LinkedHashMap<String, Object> {
    private static final long serialVersionUID = 1L;
    //当前页码
    private int page;
    //每页条数
    private int limit;

    public Query(Map<String, Object> params) {
        this.putAll(params);

        //分页参数
        if (MapUtils.isNotEmpty(params)) {
            this.page = Objects.nonNull(params.get("page")) ? Integer.parseInt(params.get("page").toString()) : 1;
            this.limit = Objects.nonNull(params.get("limit")) ? Integer.parseInt(params.get("limit").toString()) : 10;
        } else {
            this.page = 1;
            this.limit = 10;
        }
        this.put("offset", (page - 1) * limit);
        this.put("page", page);
        this.put("limit", limit);


        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        if (Objects.nonNull(params.get("sidx"))) {
            String sidx = params.get("sidx").toString();
            this.put("sidx", SQLFilter.sqlInject(sidx));
        }
        if (Objects.nonNull(params.get("order"))) {
            String order = params.get("order").toString();
            this.put("order", SQLFilter.sqlInject(order));
        }
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }
}
